package com.carlton.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.carlton.api.DistributedIdFeign;
import com.carlton.common.Result;
import com.carlton.common.Status;
import com.carlton.exception.LeafServerException;
import com.carlton.exception.NoKeyException;
import com.carlton.service.IDGen;

@RestController
public class DistributedIdContorller implements DistributedIdFeign {

	@Autowired
	IDGen snowflakeIDGen;

	@Override
	public String getSnowflakeID(String key) {
		return get(key, snowflakeIDGen.get(key));
	}

	private String get(String key, Result id) {
		Result result;
		if (key == null || key.isEmpty()) {
			throw new NoKeyException();
		}

		result = id;
		if (result.getStatus().equals(Status.EXCEPTION)) {
			throw new LeafServerException(result.toString());
		}
		return String.valueOf(result.getId());
	}
}
